import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class SystemGUI extends JFrame {
    private JTextField productField;
    private JTextArea resultArea;
    private JButton compareButton;
    private JProgressBar progressBar;

    public SystemGUI() {
        init();
        setTitle("多平台比价系统");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(600, 400);
        setLocationRelativeTo(null);
    }
    private void init() {
        setLayout(new BorderLayout());
        productField = new JTextField(20);
        resultArea = new JTextArea(10, 40);
        resultArea.setEditable(false);
        resultArea.setText("输入商品名进行查询...");
        compareButton = new JButton("比价");
        compareButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (productField.getText().equals("")) {
                    JOptionPane.showMessageDialog(SystemGUI.this, "请输入商品名称！", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }
                Comparison comparison = new Comparison();
                resultArea.setText(comparison.Compare());
            }
        });
        progressBar = new JProgressBar();
        progressBar.setStringPainted(true);
        progressBar.setIndeterminate(true);
        //进度条在点击比对按钮后一秒内加载到100%
        compareButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (productField.getText().equals("")) {
                    return;
                }
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        for (int i = 0; i <=100; i++) {
                            progressBar.setValue(i);
                            try {
                                //设定进度条为确定模式
                                progressBar.setIndeterminate(false);
                                Thread.sleep(10);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
               }).start();
            }
        });
        JPanel panel = new JPanel();
        JPanel progressPanel = new JPanel();
        panel.add(new JLabel("商品名称:", JLabel.RIGHT));
        panel.add(productField);
        panel.add(compareButton);
        progressPanel.add(progressBar);
        panel.add(new JLabel("︾比价结果如下︾"));
        add(panel, BorderLayout.NORTH);
        add(progressPanel, BorderLayout.SOUTH);
        add(new JScrollPane(resultArea));
    }
}
